<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2022-08-25 21:33:51
 * @LastEditors: CHINAKAIYUAN
 * @Description: 
 */

namespace App\Models;

use App\Repositories\FinanceVoucherRepository;
use App\Traits\AttachmentTrait;
use App\Traits\AutoCodeTrait;
use App\Traits\CommonUserTrait;
use App\Traits\SoftDeletesTrait;
use App\Traits\VoucherTrait;

class MarketDelivery extends BaseModel
    {
    use AutoCodeTrait;
    use AttachmentTrait;
    use VoucherTrait;
    use SoftDeletesTrait;
    use CommonUserTrait;
    public $timestamps = true;
    public $table = "sys_market_delivery";
    protected $guarded = [];
    //附件
    public $attachmentkey = "code";

    protected $casts = [];

    /**
     * Summary of carry
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * @author sunkaiyuan
     */
    public function carry()
        {
        return $this->belongsTo(ComprehensiveCarry::class);
        }
    /**
     * Summary of car
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * @author sunkaiyuan
     */
    public function car()
        {
        return $this->belongsTo(ComprehensiveCar::class);
        }
    /**
     * 标识
     *
     * @var string
     */
    protected $ACSign = 'MARKET_RETAIL';

    /**
     * 编号所用的字段
     *
     * @var string
     */
    protected $ACCode = 'code';

    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'status_with_finance');
            });
        }
    public function tax()
        {
        return $this->belongsTo(Dic::class, "tax_id", "key")->where(function ($q)
            {
            $q->where("code", 'FinanceTax');
            });
        }
    public function customer()
        {
        return $this->belongsTo(Company::class);
        }
    public function details()
        {
        return $this->hasMany(MarketDeliveryDetails::class, "code", "code");
        }
    public function extra_cost_details()
        {
        return $this->hasMany(MarketDeliveryExtraCost::class, "code", "code");
        }
    public function fstatus()
        {
        return $this->belongsTo(Dic::class, "fstatus_id", "key")->where(function ($q)
            {
            $q->where("code", 'Finance_Status');
            });
        }

    public function department()
        {
        return $this->belongsTo(Department::class);
        }


    public function finance($orders = null)
        {
        $v = $orders ?? $this;
        if ($v->status_id == 2)
            return $v->voucher;
        if ($v->status_id != 1) {
            fail("单据非审核状态！，无法财审！");
            }

        //借应收账款
        //贷主营业务收入
        $credit_amount = 0;
        $details       = [];
        $tax_rate      = null;
        $v->details->filter(function ($v) use (&$credit_amount, &$details, &$tax_rate)
            {
            $order_str     = isEmpty($v->orderno) ? "" : "[{$v->orderno}]";
            $credit_amount += $v['amount'];
            $details[]     = FinanceVoucherRepository::mergeVoucher(1122, $order_str . $v->finance_remark, $v['amount'], 0, array_merge($v->toArray(), [
                'quantity'    => $v->quantity,
                'se_quantity' => $v->se_quantity,
                'mi_quantity' => $v->mi_quantity,
                'price'       => $v->se_price,
                'company_id'  => $v->main_customer_id
            ]), 0, $v->tax_id);

            if ($tax_rate == null)
                $tax_rate = $v->material?->tax_rate;
            fauditSave($v);
            });
        $extra_cost = 0;
        $ex_remark  = "";
        $v->extra_cost_details->filter(function ($v) use (&$extra_cost, &$ex_remark, &$details, &$tax_rate)
            {
            $extra_cost += $v['amount'];
            $ex_remark .= "[{$v->extra_cost}]{$v->finance_remark}";
            $details[]  = FinanceVoucherRepository::mergeVoucher(5051, "[{$v->extra_cost}]{$v->finance_remark}", 0, $v['amount'], array_merge($v->toArray(), [
                'company_id' => $v->main->customer_id,
            ]), 0, $v->tax_id);
            });
        if ($v->extra_cost_details->count() > 0)
            $details[] = FinanceVoucherRepository::mergeVoucher(1122, "[额外费用]" . $ex_remark, $extra_cost, 0, array_merge($v->toArray(), [
                'quantity'    => 0,
                'mi_quantity' => 0,
                'price'       => 0,
                'company_id'  => $v->customer_id
            ]), 0, $v->tax_id);

        if ($v->tax_id == 1) {
            $notax_amount = $credit_amount / (1 + $tax_rate / 100);
            $tax_amount   = $credit_amount - $notax_amount;
            $details[]    = FinanceVoucherRepository::mergeVoucher(22210105, $v['summary'], 0, $tax_amount);
            }
        else {
            $notax_amount = $credit_amount;
            }
        $details[] = FinanceVoucherRepository::mergeVoucher(5001, $v['summary'], 0, $notax_amount);
        $voucher   = FinanceVoucherRepository::CreateVoucher($v->billdate ?? $v->created_at, 1, $details, $v, $v->voucher?->id);
        //审核凭证
        fauditSave($v);
        return FinanceVoucherRepository::auditVoucher($voucher);
        }
    public function nofinance($orders = null)
        {
        $v = $orders ?? $this;
        if ($v->status_id == 1)
            return $v->voucher;
        if ($v->status_id != 2) {
            fail("非财审状态！，无法取消财审！");
            }
        if (($v->voucher?->status_id ?? 0) != 0) {
            fail("凭证【{$v->voucher->code}】已记账！ 操作失败！");
            }
        $v->details->filter(function ($v)
            {
            fauditSave($v, false);
            });

        return fauditSave($v, false);
        }
    }
